package com.gzhu.knowledgeAdmin.parammanage;

import com.gzhu.knowledgeAdmin.common.dto.param.ParamAddRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamDeleteRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamGetRequest;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.entity.IntentionJudgeCondition;
import com.gzhu.knowledgeAdmin.repository.IntentionJudgeConditionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class IntentionJudgeConditionParamCRUD implements ParamCRUD<IntentionJudgeCondition> {

    @Autowired
    private IntentionJudgeConditionRepository intentionJudgeConditionRepository;

    @Override
    public List<String> getSimpleList() {
        List<IntentionJudgeCondition> list = intentionJudgeConditionRepository.findAll();
        return list.stream().map(intentionJudgeCondition -> intentionJudgeCondition.getName()).collect(Collectors.toList());
    }

    @Override
    public Page<IntentionJudgeCondition> getList(ParamGetRequest paramGetRequest) {
        IntentionJudgeCondition intentionJudgeCondition = new IntentionJudgeCondition();
        intentionJudgeCondition.setName(paramGetRequest.getValue());

        ExampleMatcher matcher = ExampleMatcher.matching()
                //contains 模糊匹配
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<IntentionJudgeCondition> example = Example.of(intentionJudgeCondition, matcher);

        Pageable pageable = PageRequest.of(paramGetRequest.getPageNum() - 1, paramGetRequest.getPageSize());

        return intentionJudgeConditionRepository.findAll(example, pageable);
    }

    @Override
    public void addParam(ParamAddRequest paramAddRequest) {
        String value = paramAddRequest.getValue();

        IntentionJudgeCondition intentionJudgeConditionByName = intentionJudgeConditionRepository.getIntentionJudgeConditionByName(value);
        if (intentionJudgeConditionByName != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "对应参数已经存在");
        }

        IntentionJudgeCondition intentionJudgeCondition = new IntentionJudgeCondition();
        intentionJudgeCondition.setName(value);
        intentionJudgeConditionRepository.save(intentionJudgeCondition);
    }

    @Override
    public void deleteParam(ParamDeleteRequest paramDeleteRequest) {
        List<Integer> ids = paramDeleteRequest.getIds();

        intentionJudgeConditionRepository.deleteAllByIdInBatch(ids);
    }
}
